"""
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    created by lei.chang on '25/09/2023'
    comment: 锁屏dialog
"""
import asyncio
from datetime import datetime as dt
from datetime import timedelta
from PyQt5.QtWidgets import QDialog, QLabel, QProgressBar, QVBoxLayout
from PyQt5.QtCore import QThread, pyqtSignal, Qt, QTimer
from typing import Callable

from project.service.digiccy import DigiccyService


# 1. 耗时工作线程 -------------------------------------------------
class Worker(QThread):
    step = pyqtSignal(int)   # 进度 0~100
    done = pyqtSignal()      # 任务完成

    def __init__(self, parent=None, coroutine_func: Callable = None):
        """
        :param parent:
        :param coroutine_func:
        """
        super().__init__(parent)
        self.coroutine_func = coroutine_func

    def run(self):
        """
        :return:
        """
        if self.coroutine_func is not None:
            asyncio.run(self.coroutine_func())

        self.done.emit()


# 2. 锁屏 Dialog （异步执行 & 自关闭） -----------------------------
class LockDialog(QDialog):
    def __init__(self,
                 parent=None,
                 window_title='',
                 label_text='',
                 coroutine_func=None):
        """
        :param parent:
        :param window_title:
        :param label_text:
        """
        super().__init__(parent)
        self.setWindowTitle(window_title)
        self.setFixedSize(320, 120)
        self.setWindowFlags(Qt.Dialog | Qt.CustomizeWindowHint | Qt.WindowTitleHint)

        self.label = QLabel(label_text, self)
        self.bar = QProgressBar(self)
        self.bar.setRange(0, 100)

        lay = QVBoxLayout(self)
        lay.addWidget(self.label)
        lay.addWidget(self.bar)

        # 异步线程
        self.worker = Worker(self, coroutine_func)
        # self.worker.step.connect(self.bar.setValue)
        self.worker.done.connect(self.on_finished)
        self.worker.start()          # 打开就开工

    def on_finished(self):
        self.label.setText("任务完成！即将自动关闭")
        # 1 秒后自动关
        QTimer.singleShot(1000, self.accept)

    # 屏蔽关闭按钮 & ESC
    def closeEvent(self, event):
        event.ignore()

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Escape:
            event.ignore()
        else:
            super().keyPressEvent(event)
